<template>
  <div class="com-container">
      <div class="com-chart" ref='hot_ref'></div>
      <span class="iconfont arr-left" @click="toLeft" :style="comStyle">&#xe6ef;</span>
      <span class="iconfont arr-right" @click="toRight" :style="comStyle">&#xe6ed;</span>
      <span class="cat-name" :style="comStyle">{{catName}}</span>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import {getThemeValue} from '@/utils/theme_utils'
export default {
    data(){
        return{
            //echarts实例对象
            chartInstance:null,
            //保存服务器返回的数据
            allData:null,
            currentIndex:0, //当前所展示的一级分类数据
            titleFontSize:0, //标题文字大小
        }
    },
    created() {
        //在组件创建的时候进行webSocket回调函数的注册
        this.$socket.registerCallBack('hotData',this.getData)
    },
    mounted(){
        this.initChart()
        // this.getData()
        window.addEventListener('resize',this.screenAdapter)
        //页面加载完成主动进行屏幕的适配
        this.screenAdapter()
        //使用websocket发送给服务器
        this.$socket.send({
            action:'getData',
            socketType:'hotData',
            chartName:'hot',
            value:''
        })
    },
    destroyed() {
        // 在组件销毁时，将监听器取消（防止内存泄漏）
        window.removeEventListener('resize',this.screenAdapter)
        //在组件销毁的时候进行webSocket回调函数的取消
        this.$socket.unRegisterCallBack('hotData')
    },
    computed:{
        ...mapState(['theme']),
        catName(){
            if(!this.allData){
                return ''
            }else{
                return this.allData[this.currentIndex].name
            } 
        },
        comStyle(){
            return {
                fontSize: this.titleFontSize + 'px',
                color: getThemeValue(this.theme).titleColor
            }
        }
    },
    watch:{
        theme(){
            this.chartInstance.dispose()  //销毁图表
            this.initChart()  //以最新的主题初始化图表
            this.screenAdapter()  //重新适配屏幕
            this.updatChart()  //更新数据
        }
    },
    methods:{
        //初始化echarts实例对象
        initChart(){
            this.chartInstance = this.$echarts.init(this.$refs.hot_ref,this.theme)
            //对图表初始化配置
            const initOption = {
                title:{
                    text:'▎ 热销商品的占比',
                    top:20,
                    left:20,
                },
                legend:{
                    top:'15%',
                    icon:'circle'
                },
                tooltip:{
                    show:true,
                    formatter: arg =>{
                        const thirdCategory = arg.data.children //二级分类下的三级分类，在seriesData下的children中
                        //计算所有三级分类的总和
                        let total = 0
                        thirdCategory.forEach(item=>{
                            total += item.value
                        })
                        let retStr = ''
                        thirdCategory.forEach(item=>{
                            retStr += `
                            ${item.name} : ${parseInt(item.value / total * 100) + '%'}
                            <br/>
                            `
                        })
                        return retStr
                    }
                },
                series:[
                    {
                        type:'pie',
                        label:{
                            show:false
                        },
                        emphasis:{
                            label:{
                                show:true,
                            },
                            labelLine:{
                                show:false
                            }
                        }
                    }
                ]
            }
            this.chartInstance.setOption(initOption)
        },
        // 获取服务器数据
        getData(ret){
            // let {data:ret} = await this.$http.get('hotproduct')
            this.allData = ret
            this.updatChart()
        },
        // 更新图表
        updatChart(){
            //处理图表数据
            const legendData = this.allData[this.currentIndex].children.map(item=>{
                return item.name
            })
            const seriesData = this.allData[this.currentIndex].children.map(item=>{
                return {
                    name: item.name,
                    value: item.value,
                    children: item.children
                }
            })
            const updataOption = {
                legend:{
                    data: legendData
                },
                series:[
                    {
                        data:seriesData
                    }
                ]
            }
            this.chartInstance.setOption(updataOption)
        },
        //当浏览器窗口发生变化时，改变图表的大小
        screenAdapter(){
            //图表标题的大小
            this.titleFontSize = this.$refs.hot_ref.offsetWidth / 100 * 3.6
            //和分辨率大小相关的配置项
            const adapterOption = {
                title:{
                    textStyle:{
                        fontSize:this.titleFontSize
                    }
                },
                legend:{
                    itemWidth: this.titleFontSize,
                    itemHeight: this.titleFontSize,
                    itemGap: this.titleFontSize / 2,
                    textStyle:{
                        fontSize: this.titleFontSize / 2
                    }
                },
                series:[
                    {
                        radius:this.titleFontSize * 5,
                        center:['50%','60%']
                    }
                ]
            }
            this.chartInstance.setOption(adapterOption)
            // 调用图表的resize方法
            this.chartInstance.resize()
        },
        toLeft(){
            this.currentIndex--
            if(this.currentIndex < 0){
                this.currentIndex = this.allData.length - 1
            }
            this.updatChart()
        },
        toRight(){
            this.currentIndex++
            if(this.currentIndex >= this.allData.length){
                this.currentIndex = 0
            }
            this.updatChart()
        }
    }
}
</script>

<style lang='less' scoped>
.arr-left{
  position: absolute;
  left:10%;
  top:50%;
  transform: translateY(-50%);
  color: white;
  cursor: pointer;
}
.arr-right{
  position: absolute;
  right:10%;
  top:50%;
  transform: translateY(-50%);
  color: white;
  cursor: pointer;
}
.cat-name{
    position: absolute;
    left:80%;
    bottom: 40px;
    color: white;
}
</style>